/**
 * Copyright (c) 2016-2017, xujie 徐杰 (jxtpro@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jxtpr.upload;

import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
/**
 * layui上传文件 upload 上传组件
 */
public class UploadTestController extends Controller{
	public static final String[] imgexts = {"png","jpg"};
	/**
	 * 上传
	 */
	public void upload(){
		renderJson(doUpload(getFile()));
	}
	/**
	 * 可做判断 图片大小/ext/...
	 */
	public Ret doUpload(UploadFile uf){
		if(uf == null ){
			return result(111, "请选择图片", null);
		}
		String fileName = uf.getFile().getName(); //先简单判断 ext 
		if(!isInexts(fileName)){
			return result(111, "支持[png,jpg]图片", null);
		}
		//小于等于 200 k 图片
		if(uf.getFile().length() > 1024 * 200){ 
			return result(111, "请选择图片", null);
		}
		//TODO 可新增param 做其他业务操作 如连接 阿里云服务器 oss /七牛云 ] 存本地数据库记录数据
		return result(0, "上传成功", null); // code == 0 表示上传成功
	}
	/**
	 * 简单验证是否符合图片扩展名称
	 */
	public boolean isInexts(String fileName){
		for (int i = 0; i < imgexts.length; i++) {
			if(fileName.contains(imgexts[i]) && fileName.charAt(fileName.lastIndexOf(imgexts[i]) -1) == '.'){
				return true;
			}
		}
		return false;
	}
	/**
	 * 简单 json to
	 */
	public Ret result(Object code,String msg,Object data){
		return Ret.create("msg",msg).set("code", code).set("data", data);
	}

	public void index(){
		render("index.html");
	}
}
